package com.lcxw.hxzbadmin.controller.membercontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbadmin.entity.requestbean.GetMemberDynamicRequestParams;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.StringUtil;

@RestController
@CrossOrigin
@RequestMapping("admin/user")
public class MemberManagerController {

    private Logger logger = LoggerFactory.getLogger(MemberManagerController.class);

//    private YwpdMemberService ywpdMemberService = new YwpdMemberService();

    @Resource
    YwpdMemberService ywpdMemberService;

    /**
     * 1、动态查询用户接口
     * @param requestParams
     * @return
     */
    @PostMapping("/get")
    public Response getMemberDynamic(
        @Valid @RequestBody GetMemberDynamicRequestParams requestParams) {
        logger.info("admin query user.");
        Response response = new Response();

        String fromRegTime = requestParams.getFromRegTime();
        String toRegTime = requestParams.getToRegTime();

        String idOrName = requestParams.getIdOrName();

        Integer sign = requestParams.getSign();
        Integer liveStatus = requestParams.getLiveStatus();
        Integer cancelled = requestParams.getCancelled();

        int pageIndex = requestParams.getPageIndex();
        int pageSize = requestParams.getPageSize();
        pageIndex = (pageIndex - 1) * pageSize;

        Map<String, Object> data = new LinkedHashMap<>();
        List<YwpdMember> members = new ArrayList<>();
        int count,sum;

        //如果攜帶了UserId或者UserName，則根據該參數查詢
        if (!StringUtil.isEmpty(idOrName)) {
            YwpdMember ywpdMember;
            try {
                long userId = Long.parseLong(idOrName);
                ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
            } catch (NumberFormatException e) {
                try {
                    ywpdMember = ywpdMemberService.selectYwpdMemberByUserName(idOrName);
                } catch (Exception ex) {
                    return Response.dbFail(logger, "admin query member by userName");
                }
            } catch (Exception e) {
                return Response.dbFail(logger, "admin query member by userId");
            }
            //用戶不存在
            if (null == ywpdMember || ywpdMember.getCancelled() != cancelled) {
                return Response.common(logger, "admin query member not exist.", ErrorCode.INVALID_PARAM,
                    "member not exist.", null);
            }
            members.add(ywpdMember);
            count = 1;
            sum = 1;
            data.put("count", count);
            data.put("sum",sum);
            data.put("members", members);
            response.setDesc("success");
            response.setData(data);
            return response;
        }

        //如果沒有攜帶id或者name，則按照攜帶的其他條件查詢
        try {
            members = ywpdMemberService
                .selectMemberDynamic(fromRegTime, toRegTime, sign, liveStatus, cancelled, pageIndex,
                    pageSize);
            count = members.size();
            sum = ywpdMemberService.selectCountOfMemberDynamic(fromRegTime, toRegTime, sign, liveStatus, cancelled);
            data.put("sum",sum);
            data.put("count", count);
            data.put("members", members);
            response.setDesc("success");
            response.setData(data);
        } catch (Exception e) {
            return Response.dbFail(logger, "admin query member dynamic");
        }

        return response;

    }


    /**
     * 2、注销用户接口
     * @param requestParams
     * @return
     */
    @PostMapping("/cancelled")
    public Response cancelMember(@RequestBody JSONObject requestParams){
        logger.info("adminUser {} cancel the member {}",requestParams.getString("adminName"),requestParams.getString("userId"));

        if (StringUtil.isEmpty(requestParams.getString("userId"))){
            return Response.common(logger,"userId 为空。", ErrorCode.PARAM_ERROR,"userId不能为空。",null);
        }

        long userId=Long.parseLong(requestParams.getString("userId"));

        Response response = new Response();

        YwpdMember ywpdMember;
        try {
            ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
            ywpdMember.setCancelled(1);
            ywpdMemberService.updateYwpdMember(ywpdMember);
            response.setDesc("success");
        } catch (Exception e) {
            return Response.dbFail(logger,"operate member "+userId );
        }

        return response;
    }

    /**
     * 3、恢复用户
     * @param requestParams
     * @return
     */
    @PostMapping("/recover")
    public Response recoverMember(@RequestBody JSONObject requestParams){
        logger.info("adminUser {} recover the member {}",requestParams.getString("adminName"),requestParams.getString("userId"));

        if (StringUtil.isEmpty(requestParams.getString("userId"))){
            return Response.common(logger,"userId 为空。",ErrorCode.PARAM_ERROR,"userId不能为空。",null);
        }

        Response response = new Response();

        long userId=Long.parseLong(requestParams.getString("userId"));
        YwpdMember ywpdMember;
        try {
            ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
            ywpdMember.setCancelled(0);
            ywpdMemberService.updateYwpdMember(ywpdMember);
            response.setDesc("success");
        } catch (Exception e) {
            return Response.dbFail(logger,"operate member "+userId );
        }

        return response;
    }



}
